<?php
class indexClassAction extends Action
{
	public function cgSubBefore($table){
		$sql = 'SELECT * FROM `[Q]zbcg_new` where status=1 order BY id desc ';
		$s = " and mid in (";
		$list = $this->db->getall($sql);
		$s .= getSplitStr($list, "id");
		$s .= ")";
		return $s;
	}
	/**
	 * 待合并项目
	 */
	public function getSubDataAjax(){
//		$sql = 'SELECT a.*,b.projectname FROM `[Q]zbcg_new_info` as a inner join `[Q]zbcg_new` as b on a.mid=b.id where b.status=1 and a.id not in (select subinfoid from [Q]zbcg_newinfo2mergepro) order by a.id desc ';
		$sql = 'SELECT a.*,b.projectname FROM `[Q]zbcg_new_info` as a inner join `[Q]zbcg_new` as b on a.mid=b.id where a.id not in (select subinfoid from [Q]zbcg_newinfo2mergepro) order by a.id desc ';
		$list = $this->db->getall($sql);
		$dataArr = $list;
		$bacarr	= array(
			'totalCount'=> count($dataArr),
			'rows'		=> $dataArr
		);
		echo json_encode($bacarr);
	}
	
	public function getMergeSubDataAjax(){
		$sql = 'SELECT a.* FROM [Q]zbcg_merge_project as a  order by a.id desc ';
		$list = $this->db->getall($sql);
		$dataArr = $list;
		$bacarr	= array(
			'totalCount'=> count($dataArr),
			'rows'		=> $dataArr
		);
		echo json_encode($bacarr);
	}
	
	//合并项目 
	public function mergeZbcgNewinfo(){
		$ids = $_REQUEST["ids"];
		if (!$ids) {
			$this->backmsg("参数错误");
		}
		$idArr = explode(",", $ids); 
		$projectname = $_REQUEST["projectname"];
		$errMsg = "";

		
		$sql = "select a.*,b.proxycompany,b.optid from [Q]zbcg_new_info as a inner join [Q]zbcg_new as b on a.mid=b.id where a.id in (".$ids.")";
		$list = $this->db->getall($sql);
		$checkSql = "select * from [Q]zbcg_newinfo2mergepro where subinfoid in (".$ids.")";
		$checklist = $this->db->getall($checkSql);
		if (count($checklist) > 0) {
			$projectNames = "";
			for ($i = 0; $i < count($list); $i++) {
				$projectNames .= $list[$i]["name"]." ";
			}
			$errMsg = "项目 " .$projectNames." 已经合并过，不能重复合并";
			$this->backmsg($errMsg);
		}
        if (count($list) > 0) {
            $checknum = 0;
            $checkTypeTmp = '';
            $totalBudget = 0;
            $checkCompanyNum = 0;
            $checkCompanyTmp = '';

            $checkCatalogueNum = 0;
            $checkCatalogueTmp = '';

            $checkBuymodeyNum = 0;
            $checkBuymodeTmp = '';

            $checkProxycompanyNum = 0;
            $checkProxycompanyTmp = '';

            $checkProjectadminerNum = 0;
            $checkProjectadminerTmp = '';

            $checkDeptTmp = '';
            $checkDeptNum = 0;

            for ($i = 0; $i < count($list); $i++) {
                $totalBudget += intval($list[$i]["budget"]);
                if ($checkTypeTmp != $list[$i]["type"]) {
                    $checkTypeTmp = $list[$i]["type"];
                    $checknum++;
                }
                if ($checkCompanyTmp != $list[$i]["comid"]) {
                    $checkCompanyTmp = $list[$i]["comid"];
                    $checkCompanyNum++;
                }

                if ($checkCatalogueTmp != $list[$i]["catalogue"]) {
                    $checkCatalogueTmp = $list[$i]["catalogue"];
                    $checkCatalogueNum++;
                }

                if ($checkBuymodeTmp != $list[$i]["buymode"]) {
                    $checkBuymodeTmp = $list[$i]["buymode"];
                    $checkBuymodeyNum++;
                }

                if ($checkProxycompanyTmp != $list[$i]["proxycompany"]) {
                    $checkProxycompanyTmp = $list[$i]["proxycompany"];
                    $checkProxycompanyNum++;
                }

                if ($checkProjectadminerTmp != intval($list[$i]["projectadminer"])) {
                    $checkProjectadminerTmp = intval($list[$i]["projectadminer"]);
                    $checkProjectadminerNum++;
                }

                if ($checkDeptTmp != $list[$i]["dept"]) {
                    $checkDeptTmp = $list[$i]["dept"];
                    $checkDeptNum++;
                }

            }
            if ($checkCompanyNum > 1) {
                $this->backmsg("只能合并同一家机构的申报项目");
                return;
            }

            if ($checkCatalogueNum > 1) {
                $this->backmsg("只能合并同一组织形式的项目");
                return;
            }

            if ($checkBuymodeyNum > 1) {
                $this->backmsg("只能合并同一采购方式的项目");
                return;
            }

            if ($checkProxycompanyNum > 1) {
                $this->backmsg("只能合并同一代理单位的项目");
                return;
            }

            if ($checkProjectadminerNum > 1) {
                $this->backmsg("只能合并同一项目负责人的项目");
                return;
            }

            if($checkDeptNum > 1) {
                $this->backmsg("只能合并同一处室的项目");
                return;
            }

			if ($checknum == 1) {
				if ($projectname == "") {
					$projectname = $list[0]["name"];
				}
				$proxycompany = $list[0]["proxycompany"];
				$optid = $list[0]["optid"];
				if ($optid != "" ) {
					$optEntry = m("userinfo")->getone("id=".$optid);
					if ($optEntry) {
						$proxycompany = $optEntry["deptname"];
					}
				}
				$newProject = array(
					"status"=>1,
					"projecttype"=>$list[0]["type"],
					"projectname"=>$projectname,
					"buymode"=>$list[0]["buymode"],
					"uid"=>$this->adminid,
					"budget"=>$totalBudget,
					"budget_item_name"=>$list[0]["budget_item_name"],
					"funds_type"=>$list[0]["funds_type"],
					"note"=>$list[0]["other"],
					"detail"=>$list[0]["detail"],
					"upfile"=>$list[0]["upfile"],
					"applydt"=>date("Y-m-d H:i:s"),
					"proxycompany"=>$proxycompany
				);
//				print_r($newProject);exit();
				$mergeid = m('zbcg_merge_project')->insert($newProject);
				for ($i = 0; $i < count($idArr); $i++) {
					$addArr = array(
						"subinfoid"=>$idArr[$i],
						"merge_proid"=>$mergeid
					);
					m('zbcg_newinfo2mergepro')->insert($addArr);
				}
				$this->backmsg('合并成功');
			} else
			{
				$this->backmsg('要合并的项目采购类型不一致');
			}
		} else {
			$this->backmsg("对应的项目信息不存在");	
		}
	}
	//处理搜索框
	public function cgbefore($table)
	{
		$key = $this->post('key');
		$sdate = $this->post('sdate');
		$edate = $this->post('edate');
		$s   = '';
		if($key != ''){
			$s .= " and (projectname like '$key%' or `projecttype` like '$key%')";
		}
		if ($sdate != "") {
			$s .= " and optdt > '".$sdate."'";
		}
		if ($edate != "") {
			$s .= " and optdt < '".$edate."'";
		}
		return $s;
	}
	//根据批次号分类导出报表（预算金）
	public function selGroupByBatchnum(){
		$sdate = $this->post('sdate');
		$edate = $this->post('edate');
		$where = " projecttype is not null";
		if ($sdate != "") {
			$where .= " and optdt >= '".$sdate."'";
		}
		if ($edate != "") {
			$where .= " and optdt <= '".$edate."'";
		}
		$sql = 'SELECT `batchnum`,sum(`budget`) as budget, projecttype FROM `[Q]zbcg_new` where '.$where.' GROUP BY batchnum,projecttype';
		$rows = $this->db->getall($sql);
		echo json_encode($rows);
	}
	//根据采购项目类别导出报表（预算金）
	public function selGroupByProjecttype(){
		$sdate = $this->post('sdate');
		$edate = $this->post('edate');
		if ($sdate != "") {
			$where .= " and optdt >= '".$sdate."'";
		}
		if ($edate != "") {
			$where .= " and optdt <= '".$edate."'";
		}
		
		$rows = m("zbcg_new")->getrows($where, "*");
		echo json_encode($rows);
	}
	public function getlistAjax(){
//		echo "123123";exit();
		$name = $this->post("name");
		if ($name == "") {
			$pid = 0;
		} else {
			$entry = m("cgtype")->getone("name='".$name."'");
			$pid = $entry["id"];
		}
		$rows = m("cgtype")->getrows("pid=".$pid, "*");
		echo json_encode($rows);
	}
	
	public function updateApproveSubValAjax(){
		$id = $_REQUEST["id"];
		$field = $_REQUEST["f"];
		$val = $_REQUEST["v"];
		if ($field == "") {
			$this->backmsg("参数错误，字段传递有误");
		}
		$subDb = m("zbcg_approve_sub");
		$subEntry = $subDb->getone("id=".$id);
		if (!$subEntry) {
			$this->backmsg("数据有误");
		}
		$flowEntry = m("flow_set")->getone(array("table"=>"zbcg_approve"));
		if (!$flowEntry) {
			$this->backmsg("流程不存在");
		}
		$modeid = $flowEntry["id"];
		$flowBill = m("flow_bill")->getone("mid=".$subEntry["mid"]." and modeid=".$modeid);
		if (!$flowBill) {
			$this->backmsg('流程节点错误');
		}
		$nowcheckid = $flowBill["nowcheckid"];
		$checkArr = explode(",", $nowcheckid);
		$iscanUp = false;
		for ($i = 0; $i < count($checkArr); $i++) {
			if ($this->adminid == $checkArr[$i]) {
				$iscanUp = true;
			}
		}
		if (!$iscanUp) {
			$this->backmsg('您没有当前节点的修改权限');
		}

		if(empty($subEntry['mergepeojectids'])) {
            $subDb->update(array($field=>$val), "id=".$id);
            if ($field == 'proxycompany') {
                m('zbcg_new_info')->update(array('proxygov'=>$val), "id=".$subEntry['projectid']);
                m('zbcg_project_summary')->update(array('proxygov'=>$val), "projectid=".$subEntry['projectid']);
            } else {
                m('zbcg_new_info')->update(array($field=>$val), "id=".$subEntry['projectid']);
                m('zbcg_project_summary')->update(array($field=>$val), "projectid=".$subEntry['projectid']);
            }
        }else{
		    $projectids = explode(',', $subEntry['mergepeojectids']);
            for ($i = 0; $i < count($projectids); $i++) {
                $subDb->update(array($field=>$val), "id=".$projectids[$i]);
                $info = $subDb->getone("id=".$projectids[$i], 'projectid');
                if ($field == 'proxycompany') {
                    m('zbcg_new_info')->update(array('proxygov'=>$val), "id=".$info['projectid']);
                    m('zbcg_project_summary')->update(array('proxygov'=>$val), "projectid=".$info['projectid']);
                } else {
                    m('zbcg_new_info')->update(array($field=>$val), "id=".$info['projectid']);
                    m('zbcg_project_summary')->update(array($field=>$val), "projectid=".$info['projectid']);
                }
            }
        }
        $this->backmsg('修改成功');
	}
	
	
	public function getXmnbspListAjax(){
        $mid = $this->request('mid');
        $unit = $this->request('unit');
        $projectname = $this->request('projectname');
        $types = $this->request('types');
        $origins = $this->request('origins');
        $stbudget = $this->request('stbudget');
        $enbudget = $this->request('enbudget');
        $natureOfFunds = $this->request('natureOfFunds');
        $projectadminer = $this->request('projectadminer');
        $detailSubject = $this->request('detailSubject');
        $catalogue = $this->request('catalogue');
        $bugtype = $this->request('bugtype');
        $company = $this->request('company');
        $projectNameFund = $this->request('projectNameFund');
        $where = '1=1';
        if ($mid) $where .= " and a.mid=".$mid;
        if ($unit) $where .= " and a.companyname='".$unit.'\'';
        if ($projectname) $where .= " and a.name='".$projectname.'\''." or c.projectname = '".$projectname.'\'';
        if ($types) $where .= " and a.type='".$types.'\'';
        if ($origins) $where .= " and a.producing_area='".$origins.'\'';
        if ($stbudget) $where .= " and a.budget>=".$stbudget;
        if ($enbudget) $where .= " and a.budget<=".$enbudget;
        if ($natureOfFunds) $where .= " and a.funds_type='".$natureOfFunds.'\'';
        if ($projectadminer) $where .= " and a.projectadminer=".$projectadminer;
        if ($detailSubject) $where .= " and a.detail='".$detailSubject.'\'';
        if ($catalogue) $where .= " and a.catalogue='".$catalogue.'\'';
        if ($bugtype) $where .= " and a.buymode='".$bugtype.'\'';
        if ($company) $where .= " and a.proxycompany='".$company.'\'';
        if ($projectNameFund) $where .= " and a.budget_item_name='".$projectNameFund.'\'';
//        var_dump($where);exit;
        $sql = "select a.id,a.companyname,a.projectid,a.dept,a.name,a.type,a.producing_area,a.budget,a.funds_type,a.budget_item_name,a.detail,a.catalogue,a.buymode,a.proxycompany,a.projectadminer,a.note,a.mergepeojectids,a.procurecata,a.upfile,a.item_category from [Q]zbcg_approve_sub as a left join [Q]zbcg_approvesub2mergepro as b on a.id = b.subinfoid left join [Q]zbcg_merge_project as c on b.merge_proid = c.id where ".$where." order by a.mergepeojectids desc ,a.companyname asc";
//        $list = m("zbcg_approve_sub")->getrows($where, "*", "mergepeojectids desc ,companyname asc ");
        $list = $this->db->getall($sql);
		$flowLogList = m('flow_log')->getrows("mid=".$mid." and `table`='zbcg_approve'");
//		print_r($flowLogList);exit();	 
		if (count($flowLogList) > 0) {
			$modeid = $flowLogList[0]["modeid"];
//			echo $modeid;exit();
			$fieldTmpArr = m('flow_element')->getrows("`mid`='".$modeid."'",'fields,fieldstype,name,dev,data,isbt,islu,attr,iszb,issou,gongsi,placeholder','`sort`');
			$fieldarr = array();
			for ($i = 0; $i < count($fieldTmpArr); $i++) {
				$fieldarr[$fieldTmpArr[$i]['fields']] = $fieldTmpArr[$i];
			}
			//			print_r($fieldarr);exit();

            $fobj   = m('file');
			//初始表单插件元素
			$inputobj	= c('input');
			$inputobj->ismobile 	= 0;
			$inputobj->fieldarr 	= $fieldarr;
			$inputobj->flow 		= $this->flow;
			$inputobj->mid 		= $mid;
			$inputobj->initUser($this->adminid);
			for ($i = 0; $i < count($list); $i++) {
                if($list[$i]['dept']) $list[$i]['companyname'] = $list[$i]['companyname'].'-'.$list[$i]['dept'];
				$catalogue = $list[$i]["catalogue"];
				$buymode = $list[$i]["buymode"];
				$proxycompany = $list[$i]["proxycompany"];
				$projectadminer = $list[$i]["projectadminer"];
				$note = $list[$i]["note"];
				$procurecata = $list[$i]["procurecata"];
				$mergepeojectids = $list[$i]["mergepeojectids"];
				$fileInfo = m('file')->getone('');
				if($mergepeojectids != "") {
					$subinfoId = $list[$i]["id"];
					$sub2proEntry = $this->db->getone("[Q]zbcg_approvesub2mergepro", "subinfoid=".$subinfoId);
					if ($sub2proEntry) {
						$merge_proid = $sub2proEntry["merge_proid"];
						$mergeProjectInfo = m("zbcg_merge_project")->getone("id=".$merge_proid);
						$list[$i]["name"] = $mergeProjectInfo["projectname"];
                        $summary = m('zbcg_project_summary')->getone('projectid='.$list[$i]['projectid']);
                        if( empty($list[$i]["name"]) && !empty($summary['mergename']) && !empty($summary['mergeids']) ){
                            $list[$i]["name"] = $summary["mergename"];
                        }

					}

				}			
				//生成对应的表单
				$catalogue_input = $inputobj->getfieldcontval("catalogue", $catalogue);
				$buymode_input = $inputobj->getfieldcontval("buymode", $buymode);
				$proxycompany_input = $inputobj->getfieldcontval("proxycompany", $proxycompany);
				$projectadminer_input = $inputobj->getfieldcontval("projectadminer", $projectadminer);
				$note_input = $inputobj->getfieldcontval("note", $note);
				$procurecata_input = $inputobj->getfieldcontval("procurecata", $procurecata);
                $upfile_input = '';
				!empty($list[$i]['upfile']) && $upfile_input = $fobj->getstr('', '', 2, "id in (".$list[$i]["upfile"].")");

				$list[$i]["catalogue_input"] = $catalogue_input;
				$list[$i]["procurecata_input"] = $procurecata_input;
				$list[$i]["buymode_input"] = $buymode_input;
				$list[$i]["proxycompany_input"] = $proxycompany_input;
				$list[$i]["projectadminer_input"] = $projectadminer_input;
				$list[$i]["note_input"] = $note_input;
                $list[$i]["upfile_input"] = $upfile_input;
			}
		} else {
			
		}

		
		echo json_encode($list);
	}
	//获取招标情况汇总表列表
	public function getProjectInfoListAjax(){
		$rows = array();
		$uid = $this->adminid;
		$whereStr = "1=1";

        $type = $this->request("type");
        $name = $this->request("name");
        $sdate = $this->request("sdate");
        $edate = $this->request("edate");
        $ksdate = $this->request("ksdate");
        $kedate = $this->request("kedate");
        $stbudget = $this->request("stbudget");
        $enbudget = $this->request("enbudget");
        $bugtype = $this->request("bugtype");
        $comid = $this->request('comid');
        $projectadminer = $this->request("projectadminer");
        //分页
        $page = $this->request('page', 1);
        $limit = $this->request('limit', 10);

        $utype = $this->request('utype'); //管理员为真   其他人员为空
        $approveWhere = "1=1";
        $approveWhere .= "  and d.status IN (1, 0) and d.modeid = 94";

		if ($sdate) {
			$approveWhere .= " and b.addtime >= '".$sdate. " 00:00:00'";
		}
		if ($edate) {
			$approveWhere .= " and b.addtime <='". $edate. " 23:59:59'";
		}
		if(empty($sdate) && empty($edate)) $approveWhere .= " and b.addtime >='". date('Y'). "-01-01 00:00:00'";
        if ($ksdate) {
            $approveWhere .= " and b.startbiddate >= '".$ksdate."'";
        }
        if ($kedate) {
            $approveWhere .= " and b.startbiddate <= '".$kedate."'";
        }
        if ($stbudget) {
            $approveWhere .= " and b.budget >= ".$stbudget;
        }
        if ($enbudget) {
            $approveWhere .= " and b.budget <= ".$enbudget;
        }
        if ($bugtype) {
            $approveWhere .= " and b.buymode = '".$bugtype."'";
        }
        if ($comid) {
            $approveWhere .= " and b.comid = ".$comid;
        }
		if ($utype) {
		    if ($projectadminer) $approveWhere .= " and b.projectadminer=".$projectadminer;
        } else {
            $approveWhere .= " and b.projectadminer=".$uid;
        }

		if ($type) {
			$whereStr .= " and b.type='".$type."'";
		}
		if ($name) {
            $whereStr .= " and (b.name='".$name.'\''." or b.mergename = '".$name.'\')';
		}
		$list = array();
        if ($uid) {
//            $sql ="select b.id from [Q]zbcg_project_summary as b left join [Q]admin as a on a.id = b.projectadminer inner join [Q]flow_bill as d on b.mid = d.mid where " . $whereStr .' and '. $approveWhere;
//            $listSql = "select b.*, a.name as projecterName from [Q]zbcg_project_summary as b left join [Q]admin as a on a.id = b.projectadminer inner join [Q]flow_bill as d on b.mid = d.mid where " . $whereStr .' and '. $approveWhere . ' order by b.mergeids desc, b.companyname asc' .' limit '.($page-1)*$limit.','.$limit;
            $listSql = "select b.*, a.name as projecterName from [Q]zbcg_project_summary as b left join [Q]admin as a on a.id = b.projectadminer inner join [Q]flow_bill as d on b.mid = d.mid where " . $whereStr .' and b.status = 1 and '. $approveWhere . ' order by b.companyname asc, b.dept asc, b.mergename';
//            $number = $this->db->getall($sql);
            $list = $this->db->getall($listSql);
            foreach ($list as $key => $value) {
                !empty($value['mergeids']) && !empty($value['mergename']) && $list[$key]["name"] = $value["mergename"];
                !empty($value['dept']) && $list[$key]['companyname'] = $value['companyname'].'-'.$value['dept'];

                if(!empty($value['mergeids']) && !empty($value['mergename'])){
                	$countlistSql = "select b.id cid from [Q]zbcg_project_summary as b left join [Q]admin as a on a.id = b.projectadminer inner join [Q]flow_bill as d on b.mid = d.mid where " . $whereStr .' and b.mergeids = "'.$value['mergeids'].'" and b.status = 1 and '. $approveWhere . ' order by b.companyname asc, b.dept asc, b.mergename';
                    $countmergeids = $this->db->getall($countlistSql);
                	$list[$key]['countmergeids'] = count($countmergeids);
                }else{
                    $list[$key]['countmergeids'] = 0;
                }
                //var_dump($value['isprojectprogress']);exit;
                //判断是否已经增加项目进展情况
                if(empty($value['isprojectprogress'])) {
                    $dljgFlow = m('cg_dljg_flow')->getone('projectnum='.$value['id'], 'id,status');
                    if(!empty($dljgFlow) && $dljgFlow['status'] == 1) {
                        $sqlLog = 'select `step`,`name`,`optdt`,`explain` from [Q]flow_log where mid='.$dljgFlow['id'] . ' and `table` = \'cg_dljg_flow\'';
                        $log = $this->db->getall($sqlLog);
                        $logs = "\r".'执行采购审批记录:'."\r";
                        $num = 0;
                        foreach ($log as $k => $v) {
                            $num += 1;
                            $logs .= $num.'、'.$v['name'].' '.$v['explain'].' '.$v['optdt']."\r";
                        }

                        if(empty($value['mergeids'])) {
                            if(!empty($value['projectprogress'])) $logs = $value['projectprogress'].$logs;
                            m('zbcg_project_summary')->update(array('projectprogress' => $logs, 'isprojectprogress' => 1), 'id='.$value['id']);
                        } else {
                            $ids = explode(',', $value['mergeids']);
                            $projectprogress = $logs;
                            foreach ($ids as $id) {
                                $summary = m('zbcg_project_summary')->getone('projectid='.$id, 'id,projectprogress');
                                if(!empty($summary['projectprogress'])) $projectprogress = $summary['projectprogress'].$logs;
                                m('zbcg_project_summary')->update(array('projectprogress' => $projectprogress, 'isprojectprogress' => 1), 'id='.$summary['id']);
                            }
                        }

                        $logs = mb_substr($logs, 0);
                        $list[$key]['projectprogress'] = $logs;
                    }else{
                    	if(empty($value['projectprogress'])){
                            $list[$key]['projectprogress'] = '';
                    	}else{
                    		$list[$key]['projectprogress'] = $value['projectprogress'];
                    	}
                    }
                }else{
                    $list[$key]['projectprogress'] = $value['projectprogress'];
                }
                //处理空字段
                empty($value['procurecata']) && $list[$key]['procurecata'] = '';
                empty($value['projecticp']) && $list[$key]['projecticp'] = '';
                empty($value['proicptime']) && $list[$key]['proicptime'] = '';
                empty($value['aftercheckmoney']) && $list[$key]['aftercheckmoney'] = '';
                empty($value['zbmoney']) && $list[$key]['zbmoney'] = '';
                empty($value['savemoney_ys']) && $list[$key]['savemoney_ys'] = '';
                empty($value['savemoney_sj']) && $list[$key]['savemoney_sj'] = '';
                empty($value['saverate_ys']) && $list[$key]['saverate_ys'] = '';
                empty($value['saverate_sj']) && $list[$key]['saverate_sj'] = '';
                empty($value['proxygov']) && $list[$key]['proxygov'] = '';
                empty($value['signupcompany']) && $list[$key]['signupcompany'] = '';
                empty($value['proclamationdate']) && $list[$key]['proclamationdate'] = '';
                empty($value['startbiddate']) && $list[$key]['startbiddate'] = '';
                empty($value['wbtime']) && $list[$key]['wbtime'] = '';
                empty($value['zbcompany']) && $list[$key]['zbcompany'] = '';
                empty($value['issignagreement']) && $list[$key]['issignagreement'] = '';
                empty($value['projectfiles']) && $list[$key]['projectfiles'] = '';
                empty($value['gathernote']) && $list[$key]['gathernote'] = '';
                empty($value['projecterName']) && $list[$key]['projecterName'] = '';
                if($value['zbmoney']==0){
                    $list[$key]['zbmoney'] = '';
                }
                if($value['savemoney_ys']==0){
                    $list[$key]['savemoney_ys'] = '';
                }
                if($value['savemoney_sj']==0){
                    $list[$key]['savemoney_sj'] = '';
                }
                if($value['aftercheckmoney']==0){
                    $list[$key]['aftercheckmoney'] = '';
                }
            }
        }

        $bacarr	= array(
            'totalCount'=> count($list),
            'rows'		=> $list
        );
        return json_encode($bacarr);
	}

	//编辑招标情况汇总表字段
    public function editProjectSummaryAjax()
    {
        $id		= c('check')->onlynumber($this->post('id', '0'));
        $fields	= $this->post('fieldname');
        $noupf	= array('projecticp', 'proicptime', 'proxygov', 'startbiddate');
        $value	= $this->post('value');
        $info = m('zbcg_project_summary')->getone('id='.$id, 'projectid,mergeids');
        if(empty($info)) return false;
        //如果编辑的字段是$noupf中的字段且mergeids不为空时
        if(in_array(strtolower($fields), $noupf)){
            $ids = $info['mergeids'];
            if(!empty($ids)) {
                m('zbcg_project_summary')->update(array($fields => $value), "`no` is null and `projectid` in ($ids)");
                return true;
            }
        }
        m('zbcg_project_summary')->update(array($fields => $value), 'id='.$id);
        return true;
    }

    //删除招标情况汇总表的项目
    public function delProjectSummaryAjax()
    {
        $id = $this->request('id');
        //判断内部项目审批表流程是否完成
        
        $info = m('zbcg_project_summary')->getone('id='.$id);
        
        $approveSubInfo = m('zbcg_approve_sub')->getone('projectid='.$info['projectid'], 'mid');
        $approve = m('zbcg_approve')->getone('id='.$approveSubInfo['mid'].' and status = 1', 'status');
        if(empty($approve)) return json_encode(array('code'=>300, 'msg' => '内部项目审批流程未完成不能修改'));
        //处理mergeids
        $idArr = explode(",", $info['mergeids']); 
		if (count($idArr) > 1) {
			foreach ($idArr  as $k=>$v) {
				if($info['projectid'] == $v){
                    unset($idArr[$k]);
				}
			}
			$ids = implode(",",$idArr);
			foreach ($idArr as $k => $v) {
				m('zbcg_project_summary')->update(array('mergeids' => $ids), 'projectid='.$v);
			}
		}
        m('zbcg_project_summary')->update(array('status' => 2), 'id='.$id);
        return json_encode(array('code'=>200, 'msg' => 'success'));
    }

    //招标情况汇总表的项目拆包
    public function unpackingAjax()
    {
        $id = $this->post('id');
        $info = m('zbcg_project_summary')->getone('id='.$id);
        //判断内部项目审批表流程是否完成
        $approveSubInfo = m('zbcg_approve_sub')->getone('projectid='.$info['projectid'], 'mid');
        $approve = m('zbcg_approve')->getone('id='.$approveSubInfo['mid'].' and status = 1', 'status');
        if(empty($approve)) return json_encode(array('code'=>300, 'msg' => '内部项目审批流程未完成不能修改'));
        unset($info['id']);
        unset($info['mergeids']);
        if(empty($info['mergename'])) {
            $str = '拆包';
            m('zbcg_project_summary')->update(array('mergename' => $str),'id='.$id);
            $info['mergename'] = $str;
        }
        $info['no'] = $id;
        m('zbcg_project_summary')->insert($info);
        return json_encode(array('code'=>200, 'msg' => 'success'));
    }

    //获取项目负责人
	public function loadProjectadminnerAjax(){
		$list = m("userinfo")->getall("ranking='采购科项目管理人'", "id,name");
		echo json_encode($list);
	}

	//获取代理公司
    public function getDljgsAjax()
    {
        $lists = m('userinfo')->getall('deptname="代理机构"', 'id,name');
        echo json_encode($lists);
    }
	
	//获取今年的项目
	public function getNowYearProjectAjax(){
        $list = m("zbcg_new_info")->getall('projectadminer='.$this->adminid." and addtime>'".date("Y-01-01 01:01:01")."'", "id,name", 'addtime desc');
		echo json_encode($list);
	}
    
    //查询今年的项目(合并的项目作为一个项目)
	public function getNowYearMergeProjectAjax(){
        $Sql = "select id,projectid,name,companyname,mergeids,mergename,no from [Q]zbcg_project_summary   where status=1 and projectadminer=" . $this->adminid." and addtime>'".date("Y-01-01 01:01:01")."'order by addtime desc";
        $list = $this->db->getall($Sql);
        // m("zbcg_project_summary")->getall('projectadminer='.$this->adminid." and addtime>'".date("Y-01-01 01:01:01")."'", "id,projectid,name,companyname,mergeids,mergename", 'addtime desc');
        $name = "";
        foreach ($list as $key => $value) {
        	if(!empty($value['mergeids']) && !empty($value['mergename'])){
        		if($name==$value['mergename']){
                    unset($list[$key]);
        		}else{
                    $name = $value['mergename'];
                    $list[$key]['name'] = $value['mergename']."(合并后项目)";
        		}
        		if(empty($name) || $name==""){
                	$name = $value['mergename'];
                	$list[$key]['name'] = $value['mergename']."(合并后项目)";
                }
        	}
        	if(!empty($value['no']) && !empty($value['mergename']) && empty($value['mergeids'])){
                $list[$key]['name'] = $value['name']."(拆包出来的项目)";
        	}

        }
		echo json_encode($list);
	}
	/**
     * 获取项目信息合并的作为一个
     * time:2020-07-10 
     */
    public function getNowYearMergeProjectInfoAjax(){
        $id = $this->request("id");
        $where = "1=1";
        if($id) {
            $where .= " and a.id=".$id;
        }
        $where .= " and a.addtime>'".date("Y-01-01 00:00:00")."'";
        $Sql = "select a.proxygov,a.addtime,a.name,a.buymode,a.receiverdate,c.name as projectAdminerName,c.mobile,a.companyname,f.symbol,a.budget,a.proclamationdate,a.startbiddate,a.wbtime,a.mergeids,a.mergename,a.projecticp,a.zbmoney,a.zbcompany,f.comid from [Q]zbcg_project_summary as a inner join [Q]zbcg_new as f on a.mid = f.id left join [Q]admin as c on c.id = a.projectadminer where " . $where;
        $info = $this->db->getall($Sql);

        if(!empty($info[0]['mergename']) && !empty($info[0]['mergeids'])){
            $info[0]['name'] = $info[0]['mergename'];
            $Sql = "select sum(budget) as sumbudget from [Q]zbcg_project_summary  where projectid in (".$info[0]['mergeids'].") and no is null"; 
            $infosum = $this->db->getall($Sql);
            $info[0]['budget'] = $infosum[0]['sumbudget'];
        }
        empty($info[0]['receiverdate']) ? $info[0]['addtime'] = '' : $info[0]['addtime'] = date('Y-m-d', strtotime($info[0]['receiverdate']));
        !empty($info[0]['proclamationdate']) && $info[0]['proclamationdate'] = date('Y-m-d', strtotime($info[0]['proclamationdate']));
        !empty($info[0]['startbiddate']) && $info[0]['startbiddate'] = date('Y-m-d', strtotime($info[0]['startbiddate']));
        if(!empty($info)) {
            echo json_encode($info[0]);
        }else {
            echo '';
        }
    }
    
    //代理机构查询项目列表
	public function getNowZhongBiaoProjectAjax(){
		$admininfo = m('admin')->getone('id='.$this->adminid);
		//var_dump($admininfo['name']);
		$Sql = "select id,projectid,name,companyname,mergeids,mergename,no from [Q]zbcg_project_summary   where status=1 and proxygov LIKE  '" .$admininfo['name']."' and addtime>'".date("Y-01-01 01:01:01")."'order by addtime desc";
        $list = $this->db->getall($Sql);
        // m("zbcg_project_summary")->getall('projectadminer='.$this->adminid." and addtime>'".date("Y-01-01 01:01:01")."'", "id,projectid,name,companyname,mergeids,mergename", 'addtime desc');
        $name = "";
        foreach ($list as $key => $value) {
        	if(!empty($value['mergeids']) && !empty($value['mergename'])){
        		if($name==$value['mergename']){
                    unset($list[$key]);
        		}else{
                    $name = $value['mergename'];
                    $list[$key]['name'] = $value['mergename']."(合并后项目)";
        		}
        		if(empty($name) || $name==""){
                	$name = $value['mergename'];
                	$list[$key]['name'] = $value['mergename']."(合并后项目)";
                }
        	}
        	if(!empty($value['no']) && !empty($value['mergename']) && empty($value['mergeids'])){
                $list[$key]['name'] = $value['name']."(拆包出来的项目)";
        	}

        }
		echo json_encode($list);
	}

	/**
     * 获取项目信息
     * author: lv
     * email:578530370@qq.com
     * time:2020-03-11 16:17
     */
    public function getNowYearProjectInfoAjax(){
        $id = $this->request("id");
        $where = "1=1";
        if($id) {
            $where .= " and a.id=".$id;
        }
        $where .= " and a.addtime>'".date("Y-01-01 00:00:00")."'";
        $Sql = "select a.proxygov,a.addtime,a.name,a.buymode,a.receiverdate,c.name as projectAdminerName,c.mobile,b.name as companyName,f.symbol,a.budget,a.proclamationdate,a.startbiddate from [Q]zbcg_new_info as a inner join [Q]zbcg_new as f on a.mid = f.id inner join [Q]company as b on a.comid=b.id left join [Q]admin as c on c.id = a.projectadminer where " . $where;
        $info = $this->db->getall($Sql);
        empty($info[0]['receiverdate']) ? $info[0]['addtime'] = '' : $info[0]['addtime'] = date('Y-m-d', strtotime($info[0]['receiverdate']));
        !empty($info[0]['proclamationdate']) && $info[0]['proclamationdate'] = date('Y-m-d', strtotime($info[0]['proclamationdate']));
        !empty($info[0]['startbiddate']) && $info[0]['startbiddate'] = date('Y-m-d', strtotime($info[0]['startbiddate']));
        if(!empty($info)) {
            echo json_encode($info[0]);
        }else {
            echo '';
        }
    }

	//合并项目
	public function mergeZbcgNewinfoAjax(){
		
		$ids = $this->request("ids");
		//表单合并项
		$projectname = $this->request("projectname"); //申请采购项目名称
//		$catalogue = $this->request('catalogue'); //组织形式
//        $buymode = $this->request('buymode'); //采购方式
//        $proxycompany = $this->request('proxycompany'); //代理单位
//        $projectadminer = $this->request('projectadminer'); //项目负责人
//        $note = $this->request('note'); //备注

		$sericnum = $this->request("sericnum");
		if (!$ids || !$projectname || !$sericnum) {
			$this->backmsg("参数错误");
		}
		$idArr = explode(",", $ids); 
		if (count($idArr) == 1) {
			$this->backmsg("至少两个项目才有必要合并");
		}
		$errMsg = "";
		$billEntry = $this->db->getone("[Q]flow_bill", "sericnum='".$sericnum."'");
		if ($billEntry) {
			$billMid = $billEntry["mid"];
			$nowcheckid = $billEntry["nowcheckid"];
			$checkArr = explode(",", $nowcheckid);
			$iscanUp = false;
			for ($i = 0; $i < count($checkArr); $i++) {
				if ($this->adminid == $checkArr[$i]) {
					$iscanUp = true;
				}
			}
			if (!$iscanUp) {
				$this->backmsg('您没有当前节点的修改权限');
			}
		} else {
			$this->backmsg("流程不存在");
		}
		$sql = "select a.*,b.optid from [Q]zbcg_approve_sub as a inner join [Q]zbcg_approve as b on a.mid=b.id where a.id in (".$ids.")";
		$list = $this->db->getall($sql);
		$checkSql = "select * from [Q]zbcg_approvesub2mergepro where subinfoid in (".$ids.")";
		$checklist = $this->db->getall($checkSql);
		if (count($checklist) > 0) {
			$projectNames = "";
			for ($i = 0; $i < count($list); $i++) {
				$projectNames .= $list[$i]["name"]." ";
			}
			$errMsg = "项目 " .$projectNames." 已经合并过，不能重复合并";
			$this->backmsg($errMsg);
		}
		if (count($list) > 0) {
			$checknum = 0;
			$checkTypeTmp = '';
			$totalBudget = 0;
			$checkCompanyNum = 0;
			$checkCompanyTmp = '';

            $checkCatalogueNum = 0;
            $checkCatalogueTmp = '';

            $checkBuymodeyNum = 0;
            $checkBuymodeTmp = '';

            $checkProxycompanyNum = 0;
            $checkProxycompanyTmp = '';

            $checkProjectadminerNum = 0;
            $checkProjectadminerTmp = '';

            $checkDeptNum = 0;
            $checkDeptTmp = '';

            for ($i = 0; $i < count($list); $i++) {
				$totalBudget += intval($list[$i]["budget"]);
				if ($checkTypeTmp != $list[$i]["type"]) {
					$checkTypeTmp = $list[$i]["type"];
					$checknum++;
				}
				if ($checkCompanyTmp != $list[$i]["companyname"]) {
					$checkCompanyTmp = $list[$i]["companyname"];
					$checkCompanyNum++;
				}

                if ($checkCatalogueTmp != $list[$i]["catalogue"]) {
                    $checkCatalogueTmp = $list[$i]["catalogue"];
                    $checkCatalogueNum++;
                }

                if ($checkBuymodeTmp != $list[$i]["buymode"]) {
                    $checkBuymodeTmp = $list[$i]["buymode"];
                    $checkBuymodeyNum++;
                }

                if ($checkProxycompanyTmp != $list[$i]["proxycompany"]) {
                    $checkProxycompanyTmp = $list[$i]["proxycompany"];
                    $checkProxycompanyNum++;
                }
                if ($checkProjectadminerTmp != intval($list[$i]["projectadminer"])) {
                    $checkProjectadminerTmp = intval($list[$i]["projectadminer"]);
                    $checkProjectadminerNum++;
                }

                if ($checkDeptTmp != $list[$i]["dept"]) {
                    $checkDeptTmp = $list[$i]["dept"];
                    $checkDeptNum++;
                }
            }

			if ($checkCompanyNum > 1) {
				$this->backmsg("只能合并同一家机构的申报项目");
				return;
			}

            if ($checkCatalogueNum > 1) {
                $this->backmsg("只能合并同一组织形式的项目");
                return;
            }

            if ($checkBuymodeyNum > 1) {
                $this->backmsg("只能合并同一采购方式的项目");
                return;
            }

            if ($checkProxycompanyNum > 1) {
                $this->backmsg("只能合并同一代理单位的项目");
                return;
            }

            if ($checkProjectadminerNum > 1) {
                $this->backmsg("只能合并同一项目负责人的项目");
                return;
            }

            if($checkDeptNum > 1) {
                $this->backmsg("只能合并同一处室的项目");
                return;
            }

			if ($checknum == 1) {
				if ($projectname == "") {
					$projectname = $list[0]["name"];
				}
				$proxycompany = $list[0]["proxycompany"];
				$optid = $list[0]["optid"];
				if ($optid != "" ) {
					$optEntry = m("userinfo")->getone("id=".$optid);
					if ($optEntry) {
						$proxycompany = $optEntry["deptname"];
					}
				}
				$newProject = array(
					"status"=>1,
					"projecttype"=>$list[0]["type"],
					"projectname"=>$projectname,
					"buymode"=>$list[0]["buymode"],
					"uid"=>$this->adminid,
					"budget"=>$totalBudget,
					"budget_item_name"=>$list[0]["budget_item_name"],
					"funds_type"=>$list[0]["funds_type"],
					"note"=>$list[0]["other"],
					"detail"=>$list[0]["detail"],
					"upfile"=>"",
					"applydt"=>date("Y-m-d H:i:s"),
					"proxycompany"=>$proxycompany
				);

				$this->db->routinestart();
                try {
                    $mergeid = m('zbcg_merge_project')->insert($newProject);
                    //计算new_info ids
                    $projectids = '';
                    foreach($idArr as $v) {
                        $subinfo = m('zbcg_approve_sub')->getone('id='.$v, 'id,projectid');
                        $projectids .= $subinfo['projectid'].',';
                    }
                    $projectids = trim($projectids, ',');

                    //处理业务逻辑
                    for ($i = 0; $i < count($idArr); $i++) {
                        //插入内部项目审批合并记录
                        $addArr = array(
                            "subinfoid"=>$idArr[$i],
                            "merge_proid"=>$mergeid
                        );
                        m('zbcg_approvesub2mergepro')->insert($addArr);

                        //插入招标情况汇总表合并记录
                        $subinfo = m('zbcg_approve_sub')->getone('id='.$idArr[$i], 'id,projectid');
                        $mergesumlog = array('new_info_id' => $subinfo['projectid'], 'merge_proid' => $mergeid);
                        m('zbcg_summarymergepro')->insert($mergesumlog);
                        m('zbcg_project_summary')->update(array('mergeids' => $projectids, 'mergeName' => $projectname), 'projectid='.$subinfo['projectid']);
                    }
                    m("zbcg_approve_sub")->update(array("mergepeojectids"=>$ids), "id in (".$ids.")");
                    //事务提交
                    $this->db->routineend(true);
                    $this->backmsg('合并成功');
                }catch (\Exception $exception) {
                    //事务回滚
                    $this->db->routineend(false);
                    $this->backmsg('合并失败');
                }
			} else
			{
				$this->backmsg('要合并的项目采购类型不一致');
			}
		} else {
			$this->backmsg("对应的项目信息不存在");	
		}
	}

	//取消项目合并
	public function delMergeProjectAjax(){
		$id = $this->request("id");
		$sericnum = $this->request("sericnum");
		if (!$id || !$sericnum) {
			$this->backmsg("参数错误");
		}
		$billEntry = $this->db->getone("[Q]flow_bill", "sericnum='".$sericnum."'");
		if ($billEntry) {
			$billMid = $billEntry["mid"];
			$nowcheckid = $billEntry["nowcheckid"];
			$checkArr = explode(",", $nowcheckid);
			$iscanUp = false;
			for ($i = 0; $i < count($checkArr); $i++) {
				if ($this->adminid == $checkArr[$i]) {
					$iscanUp = true;
				}
			}
			if (!$iscanUp) {
				$this->backmsg('您没有当前节点的修改权限');
			}
		} else {
			$this->backmsg("流程不存在");
		}
		$approvesub2mergeProList = m("zbcg_approvesub2mergepro")->getall("subinfoid=".$id);

		if(count($approvesub2mergeProList) > 0) {
			$proid = $approvesub2mergeProList[0]["merge_proid"];
			$sub2mergeList = m("zbcg_approvesub2mergepro")->getall("merge_proid=".$proid);
			//var_dump($sub2mergeList);exit;
            $this->db->routinestart();
            try {
                foreach ($sub2mergeList as $key => $value) {
                	$subinfoId = $value["subinfoid"];
                	m("zbcg_approve_sub")->update(array("mergepeojectids"=>""), "id=".$subinfoId);
                    $subinfo = m('zbcg_approve_sub')->getone('id='.$subinfoId, 'projectid');
                    m('zbcg_project_summary')->update(array('mergeids' => '', 'mergeName' => ''), 'projectid='.$subinfo['projectid']);
                }
                m('zbcg_merge_project')->delete("id=".$proid);
                m("zbcg_approvesub2mergepro")->delete("merge_proid=".$proid);
                //$proid = 1000000;
                m("zbcg_summarymergepro")->delete("merge_proid=".$proid);
                //事务提交
                $this->db->routineend(true);
                $this->backmsg('取消合并成功');
            }catch (\Exception $exception) {
                //事务回滚
                $this->db->routineend(false);
                $this->backmsg('取消合并失败');
            }
		}else{
			$this->backmsg('该条数据不能取消合并');
		}
	}
	
	public function getApproveSubListAjax(){
		$whereStr = '1=1';
		$companyid = $this->request("companyid");
        $uid = $this->request("uid");
        if(empty($uid)) {
            $whereStr .= ' and a.projectadminer='.$this->adminid;
        }else{
            $whereStr .= ' and a.projectadminer='.$uid;
        }
		if(!empty($companyid)){
			$whereStr .= " and a.comid = ".$companyid;
		}
        $whereStr .= "  and d.status =1";
        $whereStr .= " and a.addtime>'".date("Y-01-01 00:00:00")."'";
		$sql = "select a.*,b.name as truename,c.name as companyname from [Q]zbcg_new_info as a inner join [Q]userinfo as b on a.projectadminer=b.id inner join [Q]zbcg_new as d on a.mid = d.id inner join [Q]company as c on a.comid=c.id where ". $whereStr;
		$list = $this->db->getall($sql);
		foreach ($list as $key => $value) {
		    $no = $key + 1;
            $list[$key]['id'] = $no;
        }
		echo json_encode($list);
	}

	public function getDetailSubjectAjax()
    {
        $data = m('types')->detailSubject();
        return json_encode($data);
    }

    //修改项目进展情况
    public function editProjectprogressAjax()
    {
        $id = $this->request('id');
        $content = $this->request('content');
        $content = str_replace("<br/>","&#10;",$content);
        return m('zbcg_new_info')->update(array('projectprogress' => $content), 'id='.$id);
    }
}